`
https://leetcode.cn/problems/find-longest-special-substring-that-occurs-thrice-ii/
`

/**
 * @param {string} s
 * @return {number}
 */
var maximumLength = function (s) {
  const n = s.length
  const counter = {}
  for (const c of s) counter[c] = (counter[c] || 0) + 1
  if (Object.values(counter).every((cnt) => cnt < 3)) return -1

  const check = (x) => {
    const cnt = new Array(26).fill(0)
    for (let i = 0; i < n;) {
      let j = i + 1
      while (j < n && s[j] === s[i]) j++
      const k = s.charCodeAt(i) - 'a'.charCodeAt(0)
      cnt[k] += Math.max(0, j - i - x + 1)
      if (cnt[k] >= 3) return true
      i = j
    }
    return false
  }

  let left = 0, right = n - 1
  while (left + 1 < right) {
    const mid = left + Math.floor((right - left) / 2)
    if (check(mid)) {
      left = mid
    } else[
      right = mid
    ]
  }
  return left === 0 ? -1 : left
};